import NavBar from '@/components/NavBar'
import { logout } from '@/store/actions/login'
import {
  editUserPhoto,
  editUserProfile,
  getUserProfile,
} from '@/store/actions/profile'
import { DatePicker, Drawer, List, Modal, Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import styles from './index.module.scss'

const ProfileEdit = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const profile = useSelector((state) => state.profile.profile)
  const fileRef = useRef(null)
  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])
  const [inputOpen, setInputOpen] = useState({
    visible: false,
    type: '',
  })

  const [inputList, setInputList] = useState({
    visible: false,
    type: '',
  })

  const onInputClose = () => {
    setInputOpen({
      visible: false,
      type: '',
    })
  }
  const onClickItem = (type) => {
    setInputOpen({
      visible: true,
      type,
    })
  }
  // 更改信息
  const handleSubmit = (type, value) => {
    dispatch(editUserProfile({ [type]: value }))
    onInputClose()
  }

  // 关闭抽屉2
  const onListClose = () => {
    setInputList({
      visible: false,
      type: '',
    })
  }
  const config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          fileRef.current.click()
        },
      },
      {
        title: '相册中选择',
        onClick: () => {
          fileRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: () => {
          dispatch(editUserProfile({ gender: 0 }))
          onListClose()
        },
      },
      {
        title: '女',
        onClick: () => {
          dispatch(editUserProfile({ gender: 1 }))
          onListClose()
        },
      },
    ],
  }
  // 上传文件
  const onFileChange = async (e) => {
    try {
      const file = e.target.files[0]
      const formData = new FormData()
      formData.append('photo', file)
      await dispatch(editUserPhoto(formData))
      onListClose()
      Toast.success('')
    } catch (err) {
      console.log(err)
      Toast.fail('')
    }
  }

  // 修改日期
  const onDateChange = async (date) => {
    const y = date.getFullYear()
    const m = date.getMonth() + 1
    const d = date.getDate()
    const str = `${y}-${m}-${d}`
    await dispatch(editUserProfile({ birthday: str }))
  }
  const clickLogout = () => {
    Modal.alert('提示！', '确认退出？', [
      { text: '取消', onPress: () => {} },
      {
        text: '确认',
        onPress: () => {
          dispatch(logout())
          Toast.info('已退出！')
          history.push('/login')
        },
      },
    ])
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar onLeftClick={() => history.go(-1)}>个人信息</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow="horizontal"
              extra={
                <span className="avatar-wrapper">
                  <img src={profile.photo} alt="" />
                </span>
              }
              onClick={() => setInputList({ visible: true, type: 'photo' })}
            >
              头像
            </List.Item>

            <List.Item
              arrow="horizontal"
              extra={profile.name}
              onClick={() => onClickItem('name')}
            >
              昵称
            </List.Item>

            <List.Item
              arrow="horizontal"
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => onClickItem('intro')}
            >
              简介
            </List.Item>
          </List>

          {/* 列表二：显示性别、生日 */}
          <List className="profile-list">
            <List.Item
              arrow="horizontal"
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => setInputList({ visible: true, type: 'gender' })}
            >
              性别
            </List.Item>
            <DatePicker
              mode="date"
              title="选择年月日"
              value={new Date(profile.birthday)}
              minDate={new Date(1900, 1, 1, 0, 0, 0)}
              maxDate={new Date()}
              onChange={onDateChange}
            >
              <List.Item arrow="horizontal" extra={profile.birthday}>
                生日
              </List.Item>
            </DatePicker>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input type="file" hidden />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={clickLogout}>
            退出登录
          </button>
        </div>
        <input type="file" onChange={onFileChange} hidden ref={fileRef} />
      </div>
      {/* 昵称和简介 */}
      <Drawer
        className="drawer"
        sidebar={
          inputOpen.visible ? (
            <EditInput
              onClose={onInputClose}
              onSubmit={handleSubmit}
              type={inputOpen.type}
            />
          ) : (
            <></>
          )
        }
        open={inputOpen.visible}
        position="right"
      >
        {''}
      </Drawer>

      {/* 头像和性别 */}
      <Drawer
        open={inputList.visible}
        position="bottom"
        onOpenChange={onListClose}
        sidebar={
          inputList.visible ? (
            <EditList
              config={config}
              type={inputList.type}
              onClose={onListClose}
            />
          ) : (
            <></>
          )
        }
      >
        {''}
      </Drawer>
    </div>
  )
}

export default ProfileEdit
